package org.rc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.rc.dto.MenuDto;
import org.rc.entity.Menu;
import org.rc.mapper.MenuMapper;
import org.rc.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<Menu> getMenusByIds(List<Integer> ids) {
        return list(new QueryWrapper<Menu>().in("id",ids));
    }

    @Override
    public List<Menu> getMenuList() {
        return list();
    }

    @Override
    public List<MenuDto> getMenuDtoByIds(List<Integer> ids) {
        List<MenuDto> menuDtos = list(new QueryWrapper<Menu>().in("id",ids)).stream().map(MenuDto :: getInstance).collect(Collectors.toList());
        return makePidTree(menuDtos,0);
    }


    @Override
    public List<MenuDto> getMenus() {
        List<MenuDto> menuDtos = list().stream().map(MenuDto :: getInstance).collect(Collectors.toList());
        return makePidTree(menuDtos,0);
    }

    private List<MenuDto> makePidTree(List<MenuDto> menuDtos, Integer pId){
        List<MenuDto> children = menuDtos.stream().filter(x->x.getPId().equals(pId)).sorted(Comparator.comparing(MenuDto :: getWeight)).collect(Collectors.toList());
        List<MenuDto> successor = menuDtos.stream().filter(x->!x.getPId().equals(pId)).collect(Collectors.toList());
        children.forEach(x -> x.setChildren(makePidTree(successor,x.getId())));
        return children;
    }
}
